package com.fauks.ssm.springmvc.upload;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;

@Controller
@RequestMapping("/upload")
public class UploadController {

    //单文件上传
    @RequestMapping("/single")
    public String singleUpload(MultipartFile photo, HttpSession session) {
        //String realPath = session.getServletContext().getRealPath("/upload");
        //如果用户未上传文件photo也不会为null，所以不能使用photo!=null判断
        if (!photo.isEmpty()) {
            String uploadPath = "D:\\images";
            //获取文件名称
            String originalFilename = photo.getOriginalFilename();
            try {
                //该方法要求uploadPath目录必须存在，它不会自己创建目录
                photo.transferTo(new File(uploadPath, originalFilename));
                return "uploadsuccess";
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "uploadfail";
    }

    //多文件上传,方法接收一个数组,需要使用@RequestParam表示要创建一个数组对象接收
    @RequestMapping("/multi")
    public String mulitUpload(@RequestParam MultipartFile[] photos) {
        //SpringMVC会为每个文件创建一个空文件，photos，而是empty
        for (MultipartFile photo : photos) {
            if (!photo.isEmpty()) {
                String uploadPath = "D:\\images";
                //获取文件名称,可以判断文件后缀名做文件过滤，如只能上传图片
                String originalFilename = photo.getOriginalFilename();
                try {
                    //该方法要求uploadPath目录必须存在，它不会自己创建目录
                    photo.transferTo(new File(uploadPath, originalFilename));
                } catch (IOException e) {
                    e.printStackTrace();
                    return "uploadfail";
                }
            } else {
                return "uploadfail";
            }
        }
        return "uploadsuccess";
    }
}
